/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.star.framework.excel.enhance;

import cn.hutool.poi.excel.WorkbookUtil;
import java.io.File;
import java.io.IOException;
import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.apache.poi.ss.usermodel.Workbook;

/**
 * 增强的额外的辅助方法<br>
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
public abstract class AbstractExcelHelper {

  /**
   * 获取Excel中Sheet的数量
   *
   * @param file excel文件
   * @return
   * @throws IOException
   */
  public int getSheetCount(File file) throws IOException {
    Workbook workbook = null;

    try {
      // java.io.IOException: Zip bomb detected! The file would exceed the max. ratio of compressed
      // file size to the size of the expanded data.
      // This may indicate that the file is used to inflate memory usage and thus could pose a
      // security risk.
      // You can adjust this limit via ZipSecureFile.setMinInflateRatio() if you need to work with
      // files which exceed this limit.
      // Uncompressed size: 104902, Raw/compressed size: 762, ratio: 0.007264
      // Limits: MIN_INFLATE_RATIO: 0.010000, Entry: xl/styles.xml
      ZipSecureFile.setMinInflateRatio(-1);

      workbook = WorkbookUtil.createBook(file);
      return workbook.getNumberOfSheets();
    } finally {
      if (workbook != null) {
        // 此处需要关闭文件流，否在在删除文件的时候文件处于打开状态不能删除，影响下次传输
        workbook.close();
      }
    }
  }
}
